package com.ywjh.inter.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

import com.ywjh.inter.entity.UserAddressEntity;

public class AddressDAO {

	public int insert(Connection conn, UserAddressEntity entity) throws SQLException {
		int id = 0;
		PreparedStatement ps = conn.prepareStatement("insert into user_address(address,user_id,status,name,phone) values(?,?,?,?,?)",
				Statement.RETURN_GENERATED_KEYS);
		ps.setString(1, entity.getAddress());
		ps.setInt(2, entity.getUser_id());
		ps.setInt(3, entity.getStatus());
		ps.setString(4, entity.getName());
		ps.setString(5, entity.getPhone());
		if (ps.executeUpdate() > 0) {
			ResultSet rs = ps.getGeneratedKeys();
			if (rs.next()) {
				id = rs.getInt(1);
			}
		}
		return id;
	}

	public UserAddressEntity find(Connection conn, int address_id) throws SQLException {
		UserAddressEntity entity = null;
		PreparedStatement ps = conn.prepareStatement("select * from user_address where id =?");
		ps.setInt(1, address_id);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			entity = fill(rs);
		}
		return entity;
	}

	private UserAddressEntity fill(ResultSet rs) throws SQLException {
		UserAddressEntity add = new UserAddressEntity();
		add.setId(rs.getInt("id"));
		add.setAddress(rs.getString("address"));
		add.setStatus(rs.getInt("status"));
		add.setUser_id(rs.getInt("user_id"));
		add.setPhone(rs.getString("phone"));
		add.setName(rs.getString("name"));
		return add;
	}

	public boolean update(Connection conn, UserAddressEntity entity) throws SQLException {
		boolean b = false;
		PreparedStatement ps = conn.prepareStatement("update user_address set address=?,user_id=?,status=?,name=?,phone=? where id=?");
		ps.setString(1, entity.getAddress());
		ps.setInt(2, entity.getUser_id());
		ps.setInt(3, entity.getStatus());
		ps.setString(4, entity.getName());
		ps.setString(5, entity.getPhone());
		ps.setInt(6, entity.getId());
		if (ps.executeUpdate() > 0) {
			b = true;
		}
		return b;
	}

	public List<UserAddressEntity> listByUserId(Connection conn, int user_id) throws SQLException {
		List<UserAddressEntity> list=new LinkedList<UserAddressEntity>();
		PreparedStatement ps = conn.prepareStatement("select * from user_address where user_id =? and status=1");
		ps.setInt(1, user_id);
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			UserAddressEntity entity = fill(rs);
			list.add(entity);
		}
		return list;
	}

}
